package com.Shuang.TCP2;

import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.Socket;

public class ServerThread extends Thread{
    private Socket socket;

    public ServerThread(Socket socket) {
        this.socket = socket;
    }

    @Override
    public void run() {
        try {
            // 连接上了 提示 上线了
            System.out.println(socket.getRemoteSocketAddress() + "上线了~");

            //3 连接上了之后调用字节输入流将数据读进来
            InputStream is = socket.getInputStream();

            //4 将低级的自己输入流包装成数据输入流，保持跟客户端一致
            DataInputStream dis = new DataInputStream(is);

            while (true) {
                try {
                    String rs = dis.readUTF();  //有客户端下线，会在这有异常在下面捕获
                    System.out.println(socket.getRemoteSocketAddress() + ": " + rs);

                    //将收到的消息分发给所有客户端包括自己实现群聊
                    sendMsgToAll(rs);

                } catch (Exception e) {
                    System.out.println(socket.getRemoteSocketAddress() + ": 我下线啦~");

                    //把离线的客户端从集合中去掉
                    Server.onLineSockets.remove(socket);

                    dis.close();
                    socket.close();
                    break;
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    private void sendMsgToAll(String rs) throws Exception {
        //拿到所有在线的客户端，将数据发给所有在线客户端
        for (Socket onLineSocket : Server.onLineSockets) {
            //将数据发出去，拿到字节输出流
            OutputStream os = onLineSocket.getOutputStream();
            //将字节输出流包装成数据输出流
            DataOutputStream dos = new DataOutputStream(os);
            //将数据写出去，给到当前客户端
            dos.writeUTF(rs);
            //写完刷新一下 防止没发出去
            dos.flush();
        }
    }
}
